package com.runfast.waimai.web.controller;

import com.runfast.common.dao.model.RunfastCuser;
import com.runfast.common.exception.BaseException;
import com.runfast.common.security.spring.UserDataDetails;
import com.runfast.common.service.RunfastCuseraddressService;
import com.runfast.common.service.RunfastDeliverCostService;
import com.runfast.common.utils.GPSUtil;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.common.Constants;
import com.runfast.waimai.entity.Cart;
import com.runfast.waimai.entity.CartItem;
import com.runfast.waimai.entity.CartItemKey;
import com.runfast.waimai.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 商品购物车接口
 */
@RestController("userWmCartController")
@RequestMapping(value = "/api/user/wm/cart")
public class CartController {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private RunfastShoppingtrolleyService shoppingtrolleyService;

    @Autowired
    private RunfastGoodsSellStandardService standardService;

    @Autowired
    private RunfastGoodsSellOptionService optionService;

    @Autowired
    private RunfastGoodsSellSubOptionService subOptionService;

    @Autowired
    private RunfastGoodsSellService goodsSellService;

    @Autowired
    private RunfastActivityService activityService;

    @Autowired
    private RunfastActivityTargetService activityTargetService;

    @Autowired
    private RunfastBusinessService businessService;

    @Autowired
    private RunfastFullLessService fullLessService;

    @Autowired
    private RunfastGoodsSellRecordService goodsSellRecordService;

    @Autowired
    private RunfastGoodsSellChildrenService orderItemService;


    @Autowired
    private CartService cartService;

    @Autowired
    private RunfastDeliverCostService deliverCostService;

    @Autowired
    private RunfastCuseraddressService cuseraddressService;

    @Autowired
    private RunfastGoodsSellRecordService orderService;


    /**
     * 获取用户在商家下添加的购物车列表
     *
     * @param businessId 商户id
     * @param deviceId
     * @return
     */
    @PostMapping("/list")
    public Result list(@RequestParam int businessId, @RequestParam(required = false) String deviceId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            UserDataDetails<RunfastCuser> userDataDetails = (UserDataDetails<RunfastCuser>) authentication.getPrincipal();
            RunfastCuser cuser = userDataDetails.getData();

            Integer userId = cuser.getId();

            cartService.checkGoodsIsDelete(userId,null);
            return cartService.list(businessId, userId, deviceId);
        } else {
            if (StringUtils.isBlank(deviceId)) return Result.fail(ResultCode.FAIL, "设备唯一标识不能为空");

            cartService.checkGoodsIsDelete(null,deviceId);
            return cartService.list(businessId, null, deviceId);
        }

    }

    /**
     * 获取当前用户所有的购物车
     *
     * @return
     */
    @PostMapping("/all")
    public Result all(@RequestParam(required = false) String deviceId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {

            UserDataDetails<RunfastCuser> userDataDetails = (UserDataDetails<RunfastCuser>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            RunfastCuser cuser = userDataDetails.getData();

            cartService.checkGoodsIsDelete(cuser.getId(),null);
            return Result.ok("", cartService.list(cuser.getId(),null));
        }else{
            if (StringUtils.isBlank(deviceId)) return Result.fail(ResultCode.FAIL, "设备唯一标识不能为空");

            cartService.checkGoodsIsDelete(null,deviceId);
            return Result.ok("", cartService.list(null,deviceId));
        }
    }

    /**
     * 添加购物车
     *
     * @param businessId 商户id
     * @param cart       [{"key":{"standarId":1,"optionIdPairList":[{"optionId":1,"subOptionId":2}]}, "num":5}]
     * @param deviceId   设备Id
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestParam Integer businessId, @RequestBody List<CartItem> cart, @RequestParam(required = false) String deviceId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            UserDataDetails<RunfastCuser> userDataDetails = (UserDataDetails<RunfastCuser>) authentication.getPrincipal();
            RunfastCuser cuser = userDataDetails.getData();

            Integer userId = cuser.getId();
            return cartService.add(businessId, cart, userId, null);
        } else {
            if (StringUtils.isBlank(deviceId)) return Result.fail(ResultCode.FAIL, "设备唯一标识不能为空");
            return cartService.add(businessId, cart, null, Constants.DEVICE_ID_PREFIX + deviceId);
        }


    }


    /**
     * 删除购物车
     *
     * @param businessId 商户id
     * @param cart       [{"key":{"standarId":1,"optionIdPairList":[{"optionId":1,"subOptionId":2}]}, "num":5}]
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestParam Integer businessId, @RequestBody List<CartItem> cart, @RequestParam(required = false) String deviceId) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            UserDataDetails<RunfastCuser> userDataDetails = (UserDataDetails<RunfastCuser>) authentication.getPrincipal();
            RunfastCuser cuser = userDataDetails.getData();

            Integer userId = cuser.getId();
            return cartService.delete(businessId, cart, userId, null);
        } else {
            if (StringUtils.isBlank(deviceId)) return Result.fail(ResultCode.FAIL, "设备唯一标识不能为空");
            return cartService.delete(businessId, cart, null, Constants.DEVICE_ID_PREFIX + deviceId);
        }


    }


    /**
     * 清空购物车
     *
     * @param businessId 商户id
     * @return
     */
    @PostMapping("/clear")
    public Result clear(@RequestParam int businessId, @RequestParam(required = false) String deviceId) {

        String cartId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            UserDataDetails<RunfastCuser> userDataDetails = (UserDataDetails<RunfastCuser>) authentication.getPrincipal();
            RunfastCuser cuser = userDataDetails.getData();

            Integer userId = cuser.getId();
            cartId = userId + "";
        } else {
            if (StringUtils.isBlank(deviceId)) return Result.fail(ResultCode.FAIL, "设备唯一标识不能为空");
            cartId = Constants.DEVICE_ID_PREFIX + deviceId;
        }

        HashOperations hashOperations = redisTemplate.opsForHash();
        Long delete = hashOperations.delete(Constants.REDIS_NAMESPACE_CART + cartId, businessId);
        return Result.ok("");
    }

    /**
     * 根据之前添加的购物车（保存在redis）获取订单结算信息（选择的地址，红包可以为null）
     *
     * @param userLng
     * @param userLat
     * @param businessId  商户id
     * @param toAddressId 选择的用户地址id
     * @param userRedId   红包id
     * @param token
     * @return
     */
    @PostMapping("/fillIn")
    public Result fillIn(@RequestParam double userLng, @RequestParam double userLat, @RequestParam Integer businessId, @RequestParam(required = false) Integer toAddressId, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date selfTime, @RequestParam(required = false) String selfMobile, @RequestParam(required = false) Boolean eatInBusiness, @RequestParam(required = false) Integer userRedId, @RequestParam(required = false) Integer userCouponId, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) Date bookTime, @RequestHeader String token) {
        /**
         * 高德转百度
         */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];

        Integer userId = TokenUtil.getUserId(token);
        HashOperations hashOperations = redisTemplate.opsForHash();
        Cart redisCart = (Cart) hashOperations.get(Constants.REDIS_NAMESPACE_CART + userId, businessId);
        if (redisCart == null) return Result.fail(ResultCode.FAIL, "购物车为空，请先添加购物车");
        List<CartItem> cartItemList = redisCart.getCartItems();
        for (CartItem cartItem : cartItemList) cartItem.setChecked(true);

        return cartService.fillInDiy(userLng, userLat, businessId, redisCart, toAddressId, selfTime, selfMobile, eatInBusiness, userRedId, userCouponId, bookTime, userId);

    }

    @PostMapping("/chooseCartItem")
    public Result chooseCartItem(@RequestParam Integer businessId, @RequestBody List<CartItem> cartItems) {
        UserDataDetails<RunfastCuser> principal = (UserDataDetails<RunfastCuser>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RunfastCuser cuser = principal.getData();
        Integer userId = cuser.getId();


        return cartService.chooseCartItem(businessId, cartItems, userId);


    }

    /**
     * 根据指定的购物车获取订单结算信息（选择的地址，红包可以为null）
     *
     * @param userLng
     * @param userLat
     * @param businessId  商户id
     * @param toAddressId 选择的用户地址id
     * @param userRedId   红包id
     * @param token
     * @return
     */
    @PostMapping("/fillInDiy")
    public Result fillInDiy(@RequestParam double userLng, @RequestParam double userLat, @RequestParam Integer businessId, @RequestBody List<CartItem> cartItems, @RequestParam(required = false) Integer toAddressId, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date selfTime, @RequestParam(required = false) String selfMobile, @RequestParam(required = false) Boolean eatInBusiness, @RequestParam(required = false) Integer userRedId, @RequestParam(required = false) Integer userCouponId, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) Date bookTime, @RequestHeader String token) {
        /**
         * 高德转百度
         */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];

        Integer userId = TokenUtil.getUserId(token);
        HashOperations hashOperations = redisTemplate.opsForHash();
        Cart redisCart = (Cart) hashOperations.get(Constants.REDIS_NAMESPACE_CART + userId, businessId);
        if (redisCart == null) return Result.fail(ResultCode.FAIL, "购物车为空，请先添加购物车");
        List<CartItem> cartItemList = redisCart.getCartItems();
        if (cartItemList == null || cartItemList.isEmpty()) {
            return Result.fail(ResultCode.FAIL, "购物车为空，请先添加购物车");
        } else {

            for (CartItem item : cartItemList) item.setChecked(false);

            for (CartItem cartItem : cartItems) {
                CartItemKey key = cartItem.getKey();
                CartItem redisCartItem = null;
                for (CartItem item : cartItemList) {
                    if (key != null && key.equals(item.getKey())) {
                        redisCartItem = item;
                        redisCartItem.setChecked(true);
                        break;
                    }

                }

                if (redisCartItem == null) return Result.fail(ResultCode.FAIL, "购物车中不存在该购物信息");
            }

        }

        return cartService.fillInDiy(userLng, userLat, businessId, redisCart, toAddressId, selfTime, selfMobile, eatInBusiness, userRedId, userCouponId, bookTime, userId);


    }


}
